<template>
  <div class="record-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-document-checked"></i>
        测评记录
      </h2>
      <p class="page-subtitle">查看所有已完成的心理测评记录</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <div class="section-header">
        <i class="el-icon-search"></i>
        <span>筛选条件</span>
      </div>
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="测评类型">
              <el-select
                v-model="queryParams.assessmentType"
                placeholder="请选择类型"
                style="width: 100%"
                clearable
                @change="handleQuery"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="心理健康" value="mental_health"></el-option>
                <el-option label="学习能力" value="learning_ability"></el-option>
                <el-option label="人格测试" value="personality"></el-option>
                <el-option label="情绪管理" value="emotion_management"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="5">
            <el-form-item label="测评结果">
              <el-select
                v-model="queryParams.result"
                placeholder="请选择结果"
                style="width: 100%"
                clearable
                @change="handleQuery"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="优秀" value="excellent"></el-option>
                <el-option label="良好" value="good"></el-option>
                <el-option label="一般" value="normal"></el-option>
                <el-option label="需关注" value="attention"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="5">
            <el-form-item label="任务名称">
              <el-input
                v-model="queryParams.taskName"
                placeholder="请输入任务名称"
                clearable
                @change="handleQuery"
              ></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="完成时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                @change="handleQuery"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="3">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card total">
        <div class="stat-icon">
          <i class="el-icon-data-analysis"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.total }}</h3>
          <p>总测评数</p>
        </div>
      </div>
      
      <div class="stat-card excellent">
        <div class="stat-icon">
          <i class="el-icon-medal"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.excellent }}</h3>
          <p>优秀</p>
        </div>
      </div>
      
      <div class="stat-card attention">
        <div class="stat-icon">
          <i class="el-icon-warning-outline"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.attention }}</h3>
          <p>需关注</p>
        </div>
      </div>
      
      <div class="stat-card avg-score">
        <div class="stat-icon">
          <i class="el-icon-trophy"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.avgScore }}</h3>
          <p>平均分</p>
        </div>
      </div>
    </div>

    <!-- 记录列表 -->
    <div class="table-container">
      <div class="section-header">
        <i class="el-icon-s-grid"></i>
        <span>测评记录</span>
        <div class="header-actions">
          <el-button type="text" @click="refreshData">
            <i class="el-icon-refresh"></i>
            刷新
          </el-button>
          <el-button type="text" @click="exportData">
            <i class="el-icon-download"></i>
            导出
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredRecords"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        
        <el-table-column prop="taskName" label="任务名称" min-width="180" show-overflow-tooltip></el-table-column>
        
        <el-table-column prop="assessmentType" label="测评类型" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getTypeTagType(scope.row.assessmentType)" size="small">
              {{ getTypeText(scope.row.assessmentType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="score" label="测评分数" width="100" align="center">
          <template slot-scope="scope">
            <span class="score-text" :class="getScoreClass(scope.row.score)">
              {{ scope.row.score }}分
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="result" label="测评结果" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getResultTagType(scope.row.result)" size="small">
              {{ getResultText(scope.row.result) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="150" align="center"></el-table-column>
        
        <el-table-column prop="endTime" label="完成时间" width="150" align="center"></el-table-column>
        
        <el-table-column prop="duration" label="用时" width="80" align="center">
          <template slot-scope="scope">
            {{ scope.row.duration }}分钟
          </template>
        </el-table-column>
        
        <el-table-column label="等级判断方式" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getLevelJudgeTagType(scope.row.levelJudge)" size="small">
              {{ getLevelJudgeText(scope.row.levelJudge) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewResult(scope.row)">
              查看结果
            </el-button>
            <el-button size="mini" type="info" @click="viewDetail(scope.row)">
              详细报告
            </el-button>
            <el-button size="mini" type="danger" @click="deleteRecord(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getCompleteList } from '@/api/system/assess'

export default {
  name: 'RecordList',
  data() {
    return {
      loading: false,
      
      // 查询参数
      queryParams: {
        assessmentType: '',
        result: '',
        taskName: '',
        pageNum: 1,
        pageSize: 20
      },
      
      // 日期范围
      dateRange: [],
      
      // 统计数据
      statistics: {
        total: 0,
        excellent: 0,
        attention: 0,
        avgScore: 0
      },
      
      // 记录列表
      records: [],
      total: 0
    }
  },
  
  computed: {
    // 过滤后的记录
    filteredRecords() {
      let filtered = [...this.records]
      
      // 测评类型筛选
      if (this.queryParams.assessmentType) {
        filtered = filtered.filter(record => 
          record.assessmentType === this.queryParams.assessmentType
        )
      }
      
      // 测评结果筛选
      if (this.queryParams.result) {
        filtered = filtered.filter(record => 
          record.result === this.queryParams.result
        )
      }
      
      // 任务名称筛选
      if (this.queryParams.taskName) {
        filtered = filtered.filter(record => 
          record.taskName.includes(this.queryParams.taskName)
        )
      }
      
      // 日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const [startDate, endDate] = this.dateRange
        filtered = filtered.filter(record => {
          return record.endTime >= startDate && record.endTime <= endDate
        })
      }
      
      return filtered
    }
  },
  
  async mounted() {
    console.log('测评记录页面初始化中...')
    await this.loadData()
    console.log('测评记录页面初始化完成！')
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        await this.loadRecords()
        this.calculateStatistics()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    // 加载记录列表
    async loadRecords() {
      try {
        const response = await getCompleteList({
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        })
        
        if (response.code === 200) {
          // 为每个记录添加模拟数据
          this.records = response.rows.map(record => ({
            ...record,
            assessmentType: this.getRandomAssessmentType(),
            score: Math.floor(Math.random() * 41) + 60, // 60-100分
            result: this.getRandomResult(),
            duration: Math.floor(Math.random() * 31) + 15, // 15-45分钟
            levelJudge: Math.floor(Math.random() * 4) + 1 // 1-4
          }))
          this.total = response.total
          console.log('加载了', this.records.length, '条测评记录')
        } else {
          this.$message.error(response.msg || '获取记录列表失败')
        }
      } catch (error) {
        console.error('获取记录列表失败:', error)
        this.$message.error('获取记录列表失败')
      }
    },
    
    // 随机生成测评类型
    getRandomAssessmentType() {
      const types = ['mental_health', 'learning_ability', 'personality', 'emotion_management']
      return types[Math.floor(Math.random() * types.length)]
    },
    
    // 随机生成结果
    getRandomResult() {
      const results = ['excellent', 'good', 'normal', 'attention']
      return results[Math.floor(Math.random() * results.length)]
    },
    
    // 计算统计数据
    calculateStatistics() {
      const total = this.records.length
      const excellent = this.records.filter(record => record.result === 'excellent').length
      const attention = this.records.filter(record => record.result === 'attention').length
      const avgScore = total > 0 ? Math.round(this.records.reduce((sum, record) => sum + record.score, 0) / total) : 0
      
      this.statistics = {
        total,
        excellent,
        attention,
        avgScore
      }
      
      console.log('统计数据:', this.statistics)
    },
    
    // 获取类型标签类型
    getTypeTagType(type) {
      const typeMap = {
        'mental_health': 'primary',
        'learning_ability': 'success',
        'personality': 'warning',
        'emotion_management': 'info'
      }
      return typeMap[type] || ''
    },
    
    // 获取类型文本
    getTypeText(type) {
      const textMap = {
        'mental_health': '心理健康',
        'learning_ability': '学习能力',
        'personality': '人格测试',
        'emotion_management': '情绪管理'
      }
      return textMap[type] || '未知'
    },
    
    // 获取结果标签类型
    getResultTagType(result) {
      const typeMap = {
        'excellent': 'success',
        'good': 'primary',
        'normal': 'info',
        'attention': 'danger'
      }
      return typeMap[result] || ''
    },
    
    // 获取结果文本
    getResultText(result) {
      const textMap = {
        'excellent': '优秀',
        'good': '良好',
        'normal': '一般',
        'attention': '需关注'
      }
      return textMap[result] || '未知'
    },
    
    // 获取等级判断方式标签类型
    getLevelJudgeTagType(levelJudge) {
      const typeMap = {
        1: 'warning',  // 测评预警（橙色）
        2: 'primary',  // 二阶段访谈（蓝色）
        3: 'info',     // 咨询评估（灰色）
        4: 'success'   // 综合评定（绿色）
      }
      return typeMap[levelJudge] || 'info'
    },
    
    // 获取等级判断方式文本
    getLevelJudgeText(levelJudge) {
      const textMap = {
        1: '测评预警',
        2: '二阶段访谈',
        3: '咨询评估',
        4: '综合评定'
      }
      return textMap[levelJudge] || '未知'
    },
    
    // 获取分数样式类
    getScoreClass(score) {
      if (score >= 90) return 'score-excellent'
      if (score >= 80) return 'score-good'
      if (score >= 70) return 'score-normal'
      return 'score-attention'
    },
    
    // 查询
    handleQuery() {
      console.log('执行查询:', this.queryParams, this.dateRange)
      this.calculateStatistics()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        assessmentType: '',
        result: '',
        taskName: '',
        pageNum: 1,
        pageSize: 20
      }
      this.dateRange = []
      this.handleQuery()
    },
    
    // 刷新数据
    async refreshData() {
      this.$message.info('正在刷新数据...')
      await this.loadData()
      this.$message.success('数据刷新成功')
    },
    
    // 导出数据
    exportData() {
      this.$message.info('导出功能开发中...')
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.loadRecords()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.loadRecords()
    },
    
    // 查看结果
    viewResult(record) {
      if (!record || !record.id) {
        this.$message.error('记录信息不完整，无法查看')
        return
      }
      
      if (!record.scaleIds) {
        this.$message.error('该记录没有关联量表，无法查看')
        return
      }
      
      // 跳转到结果页面
      window.open(`/questionnaire?scaleId=${record.scaleIds}&taskId=${record.id}&viewType=result`)
    },
    
    // 查看详细报告
    viewDetail(record) {
      this.$alert(`任务名称：${record.taskName}\n测评类型：${this.getTypeText(record.assessmentType)}\n测评分数：${record.score}分\n测评结果：${this.getResultText(record.result)}\n开始时间：${record.startTime}\n完成时间：${record.endTime}\n用时：${record.duration}分钟\n等级判断：${this.getLevelJudgeText(record.levelJudge)}`, '测评详情', {
        confirmButtonText: '确定',
        type: 'info'
      })
    },
    
    // 删除记录
    deleteRecord(record) {
      this.$confirm(`确定要删除测评记录"${record.taskName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        const index = this.records.findIndex(item => item.id === record.id)
        if (index > -1) {
          this.records.splice(index, 1)
          this.total = this.records.length
          this.calculateStatistics()
          this.$message.success('删除成功')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.record-list-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

/* 页面头部 */
.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title i {
  margin-right: 12px;
  color: #409EFF;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

/* 筛选区域 */
.filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
  position: relative;
}

.section-header i {
  font-size: 18px;
  color: #409EFF;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 1px;
}

/* 统计卡片 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card.total .stat-icon {
  background: linear-gradient(45deg, #909399, #b1b3b8);
}

.stat-card.excellent .stat-icon {
  background: linear-gradient(45deg, #67c23a, #85ce61);
}

.stat-card.attention .stat-icon {
  background: linear-gradient(45deg, #f56c6c, #f78989);
}

.stat-card.avg-score .stat-icon {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
}

.stat-content h3 {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.stat-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

/* 表格容器 */
.table-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 24px;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: linear-gradient(145deg, #f0f2f5 0%, #e6e8eb 100%);
  color: #2c3e50;
  font-weight: 600;
  text-align: center;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.el-table .el-table__row:hover {
  background-color: rgba(64, 158, 255, 0.05);
}

/* 分数样式 */
.score-text {
  font-weight: 600;
}

.score-excellent {
  color: #67c23a;
}

.score-good {
  color: #409EFF;
}

.score-normal {
  color: #e6a23c;
}

.score-attention {
  color: #f56c6c;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .record-list-container {
    padding: 16px;
  }
  
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filter-container,
  .table-container {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style>